package com.mojo.concurrent.concurrent_06_future;

import java.util.concurrent.*;

/**
 * FutureTask使用示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/21 9:28
 */
public class FutureTask01 {
    public static void main(String[] args) {
        FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                System.out.println("构建Callable FutureTask");
                return null;
            }
        });
        FutureTask<Boolean> booleanFutureTask = new FutureTask<>(new Runnable() {
            @Override
            public void run() {

                System.out.println("构建Runnable FutureTask");
            }
        }, false);
        Thread thread = new Thread(futureTask);
        // get方法会阻塞线程
        // get(Long timeout, TimeUnit unit)会抛出超时异常
        try {
            System.out.println("get timeout:" + futureTask.get(5L, TimeUnit.SECONDS));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        thread.start();
        try {
            System.out.println("get:" + futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        futureTask.cancel(true);

    }
}
